﻿#!/bin/bash

# 首先清除整个磁盘 
#可通过 ls -la /dev/disk/by-id/ 查看具体磁盘对应的id
#当前实例 磁盘id scsi-360022480a703662260bd68d3a30eaf19

#此id需要根据实际值做调整。
DISK_ID=scsi-360022480a703662260bd68d3a30eaf19
HOST_NAME=zpdb25
ROOT_PASSWORD=ZeroPlus2013

echo "deb cdrom:[Ubuntu 18.04.3 LTS _Bionic Beaver_ - Release amd64 (20190805)]/ bionic main restricted
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic main restricted universe 
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-updates main restricted universe  
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-security main restricted universe" > /etc/apt/sources.list


apt update


apt install --yes debootstrap gdisk zfs-initramfs


#删除所有分区
sgdisk --zap-all /dev/disk/by-id/$DISK_ID

#创建boot分区 MBR
sgdisk -a1 -n1:24K:+1000K -t1:EF02 /dev/disk/by-id/$DISK_ID

#创建boot分区 EFI (512M)
#sgdisk --new=2:48:2047 --typecode=2:EF02 --change-name=2:"BIOS boot partition" ${BLOCK_DEV}
#sgdisk    n2:48:2047 -t2:EF02 --change-name=2:"BIOS boot partition" /dev/disk/by-id/$DISK_ID

sgdisk     -n2:2M:+1024M   -t2:EF00 /dev/disk/by-id/$DISK_ID


# 创建引导文件池
 sgdisk     -n3:0:+1G      -t3:BF01 /dev/disk/by-id/$DISK_ID


#创建root分区,剩余空间都给root  Unencrypted
sgdisk     -n4:0:0        -t4:BF01 /dev/disk/by-id/$DISK_ID


#使用 lsblk 查看分区
lsblk

 #创建boot 池
 # create boot pool like /boot
 
zpool create -o ashift=12 -d \
      -o feature@async_destroy=enabled \
      -o feature@bookmarks=enabled \
      -o feature@embedded_data=enabled \
      -o feature@empty_bpobj=enabled \
      -o feature@enabled_txg=enabled \
      -o feature@extensible_dataset=enabled \
      -o feature@filesystem_limits=enabled \
      -o feature@hole_birth=enabled \
      -o feature@large_blocks=enabled \
      -o feature@lz4_compress=enabled \
      -o feature@spacemap_histogram=enabled \
      -o feature@userobj_accounting=enabled \
      -O acltype=posixacl -O canmount=off -O compression=lz4 -O devices=off \
      -O normalization=formD -O relatime=on -O xattr=sa \
      -O mountpoint=/ -R /mnt \
      bootpool /dev/disk/by-id/$DISK_ID-part3
 
 #创建root池
 #create the root path for root pool
 
 zpool create -o ashift=12 \
      -O acltype=posixacl -O canmount=off -O compression=lz4 \
      -O dnodesize=auto -O normalization=formD -O relatime=on -O xattr=sa \
      -O mountpoint=/ -R /mnt \
      rpool /dev/disk/by-id/$DISK_ID-part4
 
 # 安装系统
 
#创建路径
zfs create -o canmount=off -o mountpoint=none rpool/ROOT
zfs create -o canmount=off -o mountpoint=none bootpool/BOOT
 
 #创建分区并mount
zfs create -o canmount=noauto -o mountpoint=/ rpool/ROOT/ubuntu
zfs mount rpool/ROOT/ubuntu

zfs create -o canmount=noauto -o mountpoint=/boot bootpool/BOOT/ubuntu
zfs mount bootpool/BOOT/ubuntu
 
#创建各个系统路径，使用分离式，可以只回滚系统镜像，而不影响用户数据，比如logs等。
# Create datasets:

  zfs create                                 rpool/home
  zfs create -o mountpoint=/root             rpool/home/root
  zfs create -o canmount=off                 rpool/var
  zfs create -o canmount=off                 rpool/var/lib
  zfs create                                 rpool/var/log
  zfs create                                 rpool/var/spool

# The datasets below are optional, depending on your preferences and/or
# software choices:
 
# If you use /opt on this system:
zfs create                                 rpool/opt

# If you use /srv on this system:
zfs create                                 rpool/srv

# If you use /usr/local on this system:
zfs create -o canmount=off                 rpool/usr

zfs create                                 rpool/usr/local
 

# If this system will store local email in /var/mail:
zfs create                                 rpool/var/mail

# If this system will use Snap packages:
zfs create                                 rpool/var/snap

# If you use /var/www on this system:
zfs create                                 rpool/var/www
 
# If this system will use Docker (which manages its own datasets & snapshots):
zfs create -o com.sun:auto-snapshot=false  rpool/var/lib/docker

# If this system will use NFS (locking):
zfs create -o com.sun:auto-snapshot=false  rpool/var/lib/nfs

# A tmpfs is recommended later, but if you want a separate dataset for /tmp:
zfs create -o com.sun:auto-snapshot=false  rpool/tmp
chmod 1777 /mnt/tmp
 
#安装最小化系统
#Install the minimal system:
#debootstrap bionic /mnt

debootstrap bionic /mnt http://mirrors.163.com/ubuntu/

#for faster install you should use 163 mirrors,only for slower networking installation
# note , i only found 163 mirrors can use by install ,others may be miss something.
 

zfs set devices=off rpool

#设置系统，configure basic configure for new system

echo $HOST_NAME > /mnt/etc/hostname

echo "127.0.1.1       $HOST_NAME" >> /mnt/etc/hosts

#替换系统源
echo "deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-security main restricted universe multiverse" > /mnt/etc/apt/sources.list

#Bind the virtual filesystems from the LiveCD environment to the new system and chroot into it:
mount --rbind /dev  /mnt/dev
mount --rbind /proc /mnt/proc
mount --rbind /sys  /mnt/sys

chroot /mnt /bin/bash --login


# define system var

ROOT_PASSWORD=ZeroPlus2013

DISK_ID=scsi-360022480a703662260bd68d3a30eaf19


 
#Configure a basic system environment:
ln -s /proc/self/mounts /etc/mtab
apt update

apt install --yes nano openssh-server net-tools git curl wget htop

#设置网络，网卡名可通过ip addr show 查看,本实例为 eth0
echo "network:
  version: 2
  ethernets:
    eth0:
      dhcp4: true" > /etc/netplan/01-netcfg.yaml
      
#应用网络配置，否则启动后没有网络
netplan generate


#设置ssh默认允许root登录

sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
 

#nstall ZFS in the chroot environment for the new system:
apt install --yes --no-install-recommends linux-image-generic

apt install --yes zfs-initramfs

##Install GRUB package for BIOS

apt install --yes grub-pc

# 设置默认root密码
echo "root:${ROOT_PASSWORD}" | sudo chpasswd
 
# Enable importing bootpool

echo " [Unit]
    DefaultDependencies=no
    Before=zfs-import-scan.service
    Before=zfs-import-cache.service
    
    [Service]
    Type=oneshot
    RemainAfterExit=yes
    ExecStart=/sbin/zpool import -N -o cachefile=none bootpool
    
    [Install]
    WantedBy=zfs-import.target" > /etc/systemd/system/zfs-import-bootpool.service
    
#enable service on starting
systemctl enable zfs-import-bootpool.service

#Optional (but kindly requested): Install popcon

apt install --yes popularity-contest
#Setup system groups:
addgroup --system lpadmin
addgroup --system sambashare


###GRUB Installation and configure

#Verify that the ZFS boot filesystem is recognized: the result should shows as  $> zfs
grub-probe /boot

#Refresh the initrd files:
update-initramfs -u -k all

#命令格式1：sed 's/原字符串/新字符串/' 文件
#修改grub文件以支持zfs 引导

# sed -i 's:GRUB_CMDLINE_LINUX=\"\":GRUB_CMDLINE_LINUX=\"root=ZFS=rpool/ROOT/ubuntu\":' /etc/default/grub

echo '# If you change this file, run \\'update-grub\\' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n \\'Simple configuration\\'

GRUB_DEFAULT=0
#GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=5
GRUB_RECORDFAIL_TIMEOUT=5
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT=""
GRUB_CMDLINE_LINUX="root=ZFS=rpool/ROOT/ubuntu"

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command vbeinfo
#GRUB_GFXMODE=640x480
 
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"' > /etc/default/grub

update-grub

# Install the boot loader

# 5.6a For legacy (BIOS) booting, install GRUB to the MBR:

grub-install /dev/disk/by-id/$DISK_ID

#Do not reboot the computer until you get exactly that result message. Note that you are installing GRUB to the whole disk, not a partition.

#5.7 Verify that the ZFS module is installed:

ls /boot/grub/*/zfs.mod



##5.8 Fix filesystem mount ordering

 

#Everything else applies to both BIOS and UEFI booting:




zfs set mountpoint=legacy bootpool/BOOT/ubuntu
echo bootpool/BOOT/ubuntu /boot zfs \
      nodev,relatime,x-systemd.requires=zfs-import-bootpool.service 0 0 >> /etc/fstab

zfs set mountpoint=legacy rpool/var/log
echo rpool/var/log /var/log zfs nodev,relatime 0 0 >> /etc/fstab

zfs set mountpoint=legacy rpool/var/spool
echo rpool/var/spool /var/spool zfs nodev,relatime 0 0 >> /etc/fstab

 

#If you created a /tmp dataset:
zfs set mountpoint=legacy rpool/tmp
echo rpool/tmp /tmp zfs nodev,relatime 0 0 >> /etc/fstab

###Step 6: First Boot
# Snapshot the initial installation:
zfs snapshot bootpool/BOOT/ubuntu@install

zfs snapshot rpool/ROOT/ubuntu@install

#Exit from the chroot environment back to the LiveCD environment:
exit
cd 


# Run these commands in the LiveCD environment to unmount all filesystems:

mount | grep -v zfs | tac | awk '/\/mnt/ {print $3}' | xargs -i{} umount -lf {}

zpool export -a

#Reboot:

reboot

# Wait for the newly installed system to boot normally. Login as root.

##Create a user account:

#zfs create rpool/home/YOURUSERNAME
#adduser YOURUSERNAME
#cp -a /etc/skel/.[!.]* /home/YOURUSERNAME
#chown -R YOURUSERNAME:YOURUSERNAME /home/YOURUSERNAME

# Add your user account to the default set of groups for an administrator:

# usermod -a -G adm,cdrom,dip,lpadmin,plugdev,sambashare,sudo YOURUSERNAME

#*#  after boot and login with root. you can install basic software.

#### install a command-line environment only: for server

apt install --yes ubuntu-server


# enable google BBR , faster tcp protocol
echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
sysctl -p

# check the bbr enable status , that should show as this: net.ipv4.tcp_available_congestion_control = bbr cubic reno
sysctl net.ipv4.tcp_available_congestion_control

# check the kernel mod does start ,
lsmod | grep bbr

##**## Final Cleanup

#Optional: Delete the snapshots of the initial installation:

#$ sudo zfs destroy bootpool/BOOT/ubuntu@install
#$ sudo zfs destroy rpool/ROOT/ubuntu@install



###Step 7: (Optional) Configure Swap

#Create a volume dataset (zvol) for use as a swap device:

zfs create -V 4G -b $(getconf PAGESIZE) -o compression=zle \
      -o logbias=throughput -o sync=always \
      -o primarycache=metadata -o secondarycache=none \
      -o com.sun:auto-snapshot=false rpool/swap
      
# Configure the swap device:

 mkswap -f /dev/zvol/rpool/swap
 echo /dev/zvol/rpool/swap none swap discard 0 0 >> /etc/fstab
echo RESUME=none > /etc/initramfs-tools/conf.d/resume


#Enable the swap device:

swapon -av

 

